/**
 * JAVACC DEMO 1.0
 * @copy right iussoft company All rights reserved.
 * @Package com.apache.passport.service  
 */
package com.apache.passport.service;

import java.util.HashMap;
import java.util.Map;

import com.apache.cache.service.CacheManager;
import com.apache.cache.service.impl.LoadCacheFactory;
import com.apache.cache.service.impl.ehcache.EhcacheManagerImpl;
import com.apache.cache.util.Validator;

/**
 * description:  sso缓存工具类
 * @author qihan 创建时间：2017-9-27  
 */
public class CacheHelper {

	private static CacheHelper instance;
	private static Map<String, CacheManager> ehcaches = new HashMap<String, CacheManager>();

	private CacheHelper() {
	}

	public synchronized static CacheHelper getInstance() {
		if (null == instance) {
			instance = new CacheHelper();
		}
		return instance;
	}

	public CacheManager getCache(String cacheName) {
		if (Validator.isNull(cacheName)) {
			String defaultName = LoadCacheFactory.getInstance().getProperty("cache_default_name");
			cacheName = Validator.getDefaultStr(defaultName, "apachecache");
		}
		return getEhcacheManager(cacheName);
	}

	public Object getCacheInfo(String key, String cacheName) {
		if (Validator.isNull(cacheName)) {
			String defaultName = LoadCacheFactory.getInstance().getProperty("cache_default_name");
			cacheName = Validator.getDefaultStr(defaultName, "apachecache");
		}
		return getEhcacheManager(cacheName).getCacheCloneByKey(key);
	}

	/**
	 * 获取ehcache缓存实例
	 * @param cacheName 缓存空间名称
	 * @return
	 */
	private CacheManager getEhcacheManager(String cacheName) {
		if (null == ehcaches.get(cacheName)) {
			CacheManager cacheManager = new EhcacheManagerImpl();
			cacheManager.setCacheName(cacheName);
			ehcaches.put(cacheName, cacheManager);
		}
		return ehcaches.get(cacheName);
	}
}
